import { useEffect, useMemo, useRef, useContext } from 'react';
import { init, EChartsType, EChartsOption } from 'echarts';
import classNames from 'classnames';
import { IChartsBaseData } from 'src/interface';
import { extractData } from 'src/utils/charts';
import { useThemeDark } from 'src/hooks/theme';
import { ContentContext } from 'src/context/ContentContext';

interface IProps {
  className?: string;
  style?: React.CSSProperties;
  data?: IChartsBaseData[];
  title?: string;
  height?: number;
  showLegend?: boolean;
  options?: EChartsOption;
}

export default function AreaChart(props: IProps) {
  const { className, style, data, title, height, showLegend = true, options } = props;
  const lineEl = useRef<HTMLDivElement | null>(null);
  const example = useRef<EChartsType | null>(null);

  const { dark } = useThemeDark();
  const contentSize = useContext(ContentContext);

  const chartsOptions = useMemo(() => {
    if (!data) return {};
    const { legend, axis, options: seriesData } = extractData(data);
    return {
      darkModel: dark,
      title: {
        text: title,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985',
          },
        },
      },
      legend: {
        show: showLegend,
        data: legend,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: axis,
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: Object.keys(seriesData).map((key) => {
        return {
          name: key,
          type: 'line',
          data: seriesData[key].value,
        };
      }),
      ...options,
    };
  }, [data, title, showLegend, dark, options]);

  useEffect(() => {
    example.current && example.current.resize();
  }, [contentSize]);

  useEffect(() => {
    if (lineEl.current) {
      const charts = init(lineEl.current);
      example.current = charts;
    }
    example.current && example.current.setOption(chartsOptions);
    return () => {
      example.current && example.current.dispose();
    };
  }, [chartsOptions, dark]);

  return (
    <div
      ref={lineEl}
      className={classNames(className, 'w-[100%]')}
      style={{ ...style, height: height }}></div>
  );
}
